package com.module.basic.service.impl;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.module.basic.domain.BasicDevice;
import com.module.common.constant.UserConstants;
import com.module.common.exception.ServiceException;
import com.module.common.utils.DateUtils;
import com.module.common.utils.StringUtils;
import org.springframework.stereotype.Service;
import com.module.basic.mapper.BasicDeviceMapper;
import com.module.basic.service.IBasicDeviceService;
import com.module.common.core.text.Convert;

/**
 * 采集设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-17
 */
@Service
public class BasicDeviceServiceImpl extends ServiceImpl<BasicDeviceMapper, BasicDevice> implements IBasicDeviceService
{

    /**
     * 查询采集设备
     * 
     * @param deviceId 采集设备主键
     * @return 采集设备
     */
    @Override
    public BasicDevice selectBasicDeviceByDeviceId(Long deviceId)
    {
        return baseMapper.selectBasicDeviceByDeviceId(deviceId);
    }

    /**
     * 查询采集设备列表
     * 
     * @param basicDevice 采集设备
     * @return 采集设备
     */
    @Override
    public List<BasicDevice> selectBasicDeviceList(BasicDevice basicDevice)
    {
        return baseMapper.selectBasicDeviceList(basicDevice);
    }

    /**
     * 新增采集设备
     * 
     * @param basicDevice 采集设备
     * @return 结果
     */
    @Override
    public int insertBasicDevice(BasicDevice basicDevice)
    {
        basicDevice.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicDevice);
    }

    /**
     * 修改采集设备
     * 
     * @param basicDevice 采集设备
     * @return 结果
     */
    @Override
    public int updateBasicDevice(BasicDevice basicDevice)
    {
        basicDevice.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicDevice);
    }

    /**
     * 批量删除采集设备
     * 
     * @param deviceIds 需要删除的采集设备主键
     * @return 结果
     */
    @Override
    public int deleteBasicDeviceByDeviceIds(String deviceIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(deviceIds)));
    }

    /**
     * 删除采集设备信息
     * 
     * @param deviceId 采集设备主键
     * @return 结果
     */
    @Override
    public int deleteBasicDeviceByDeviceId(Long deviceId)
    {
        return baseMapper.deleteById(deviceId);
    }

    /**
     * 校验预算项目是否存在
     * @param basicDevice
     * @return
     */
    @Override
    public boolean checkDeviceImeiUnique(BasicDevice basicDevice) {
        Long deviceId = StringUtils.isNull(basicDevice.getDeviceId()) ? -1L : basicDevice.getDeviceId();
        BasicDevice info = baseMapper.selectOne(new LambdaQueryWrapper<BasicDevice>()
                .eq(BasicDevice::getDeviceImei, basicDevice.getDeviceImei())
                .last("limit 1"));
        if (StringUtils.isNotNull(info) && info.getDeviceId().longValue() != deviceId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 导入采集设备信息数据
     *
     * @param basicDeviceList 采集设备信息数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importBasicDevice(List<BasicDevice> basicDeviceList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(basicDeviceList) || basicDeviceList.isEmpty())
        {
            throw new ServiceException("导入采集设备信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicDevice basicDevice : basicDeviceList)
        {
            try
            {
                // 唯一性验证
                BasicDevice info = baseMapper.selectOne(new LambdaQueryWrapper<BasicDevice>().eq(BasicDevice::getDeviceImei, basicDevice.getDeviceImei()));
                if (StringUtils.isNull(info))
                {
                    basicDevice.setCreateBy(operName);
                    this.insertBasicDevice(basicDevice);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、信息 " + basicDevice.getDeviceImei() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    basicDevice.setDeviceId(info.getDeviceId());
                    basicDevice.setUpdateBy(operName);
                    this.updateBasicDevice(basicDevice);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、信息 " + basicDevice.getDeviceImei() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、信息 " + basicDevice.getDeviceImei() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、信息 " + basicDevice.getDeviceImei() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
